

#include "Heap.h"

//交换
void Swap(HPDataType* p1, HPDataType* p2)
{
	HPDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

//打印
void HeapPrint(HP* php)
{
	assert(php);
	for (int i = 0; i < php->size; ++i)
	{
		printf("%d ", php->a[i]);
	}
	printf("\n");
}

//上调logN
void AdjustUp(HPDataType* a, int child)
{
	//定位父节点下标
	int parent = (child - 1) / 2;
	while (child > 0)
	{
	//	if (a[child] > a[parent])  //大堆
		if (a[child] < a[parent])  //小堆
		{
			//交换数据
			Swap(&a[child], &a[parent]);
			//交换后更新
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//下调logN
void AdjustDwon(HPDataType* a, int size, int parent)
{
	//设左孩子较小
	int child = parent * 2 + 1;
	//当未达到堆末 进入循环
	while (child < size)
	{
		//确定real大孩子
	//	if (child + 1 < size && a[child + 1] > a[child])  //大堆
	
		//确定real小孩子
		if (child + 1 < size && a[child + 1] < a[child])  //小堆
		{
			++child;
		}
	//	if (a[parent] > a[child])  //大堆
		if (a[parent] > a[child])  //小堆
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

//初始化
void HeapInit(HP* php)
{
	assert(php);

	php->a = NULL;
	php->size = php->capacity = 0;
}

//销毁
void HeapDestroy(HP* php)
{
	assert(php); 

	free(php->a);
	php->a = NULL;
	php->size = php->capacity = 0;
}

//入堆
void HeapPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * newcapacity);
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}

		php->a = tmp;
		php->capacity = newcapacity;
	}

	php->a[php->size] = x;
	php->size++;
	//上调         插入的新数据的下标
	AdjustUp(php->a, php->size - 1);
}

//出堆
void HeapPop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	//想要删除堆头 把堆头与堆末交换
	Swap(&(php->a[0]), &(php->a[php->size - 1]));
	//删除堆末 -- 原目标值(堆头)已被删除
	php->size--;
	//将原堆末(现堆头下调置适当位置)
	AdjustDwon(php->a, php->size, 0);
}

//取堆头
HPDataType HeapTop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	return php->a[0];
}

//判空
bool HeapEmpty(HP* php)
{
	assert(php);

	return php->size == 0;
}

//堆大小
int HeapSize(HP* php)
{
	assert(php);

	return php->size;
}


